import React, {Component} from 'react';
import {Button, Modal, Select, Input, Checkbox, Row, Col, message} from "antd";
import FilterByCourse from "@/components/FilterByCourse";
import APIS from "@/apis";
import MdEditor from "@/components/MdEditor";
import MdDocShow from "@/components/MdDocShow";
import {newGuid} from "@/utils/utils";
import "./index.css"

const {Option} = Select;

interface INewQuestion {
  type: QuestionType,//试题类型
  courseList: Array<any>;//课程列表
  courseId: number;//所属课程id
  courseName: string;//所属课程名称
  visible: boolean;//弹窗显隐,
  selectItems: Array<any>;//选项集合
  answer: string;//正确答案
  analyzing: string;//解析
  id: number;//题目id
}

/*创建新的题目*/
class CreateNewQuestion extends Component <any, INewQuestion> {
  constructor(props: any) {
    super(props);
    this.state = {
      type: null,
      courseList: [],
      courseId: 0,
      visible: false,
      selectItems: [],
      answer: "",
      analyzing: "",
      courseName: "",
      id: 0
    }
    // InitMdLinks();
  }

  /*  componentWillUnmount() {
      DeleteMdLinks();
      window.location.reload();
    }*/

  componentDidMount() {
    //获取课程列表
    APIS.CourseAPI.GetCourseList({current: 1, pageSize: 99999, state: -1}).then(res => {
      this.setState({courseList: res.data})
    }).catch(e => {
      console.error(e)
    });
    let params = new URLSearchParams(this.props.history.location.search);
    if (params.has('id')) {
      const id = parseInt(params.get('id') + '');
      if (id) {
        if (id > 0) {
          APIS.ExamAPI.GetQuestionDetail({id: id}).then((resp) => {
            console.log(resp);
            const select = [];
            resp.selections?.map((ele, ind) => {
              select.push({id: newGuid(), value: ele});
            })
            setTimeout(() => {
              if (resp.content) {
                try {
                  this.questionTopic?.ResetMarkdown(resp.content);
                } catch (e) {
                  window.location.reload();
                }
              }
            })
            this.setState({
              answer: resp.answer,
              analyzing: resp.analyzing,
              courseId: resp.courseId,
              courseName: resp.courseName,
              type: resp.type,
              id: resp.id,
              selectItems: select
            });
          }).catch(e => console.error(e));
        }
      }
    }
  }

  //正确答案选择监听
  onCheckboxChange(e) {
    this.setState({answer: e.toString()});
  }

  createNewQuestion() {
    const {selectItems, analyzing, answer, courseId, type, id} = this.state;
    const selections = [];
    selectItems.map((element, index) => {
      selections.push(element.value);
    })
    const content = this.questionTopic.Submit();
    const isCanSubmit = this.checkSubmit();
    if (isCanSubmit) {
      if (id > 0) {
        //更新题目
        APIS.ExamAPI.UpdateQuestion({
          type: Number(type),
          courseId: courseId,
          content: content,
          id: id,
          selections: selections,
          answer: type === QuestionType.judgment ? Number(answer) : answer,
          analyzing: analyzing,
        }).then((resp) => {
          if (resp.code === 10000) {
            message.success("修改成功")
            this.props.history.push({
              pathname: '/teaching/exam/question'
            });
          } else {
            message.error("修改失败");
            console.log(resp);
          }
        }).catch((e) => {
          console.error(e);
        })
      } else {
        //新增题目
        APIS.ExamAPI.CreateNewQuestion({
          type: Number(type),
          courseId: courseId,
          content: content,
          selections: selections,
          answer: type === QuestionType.judgment ? Number(answer) : answer,
          analyzing: analyzing,
        }).then((resp) => {
          console.log(resp);
          if (resp.code === 10000) {
            message.success("添加成功")
            this.props.history.push({
              pathname: '/teaching/exam/question'
            });
          } else {
            message.error("添加失败");
            console.log(resp);
          }
        }).catch((e) => {
          console.error(e);
        })
      }
    }
  }

  checkSubmit() {
    const {selectItems, answer, courseId, type} = this.state;
    const content = this.questionTopic.Submit();
    if (type !== null) {
      if (type === QuestionType.select) {
        if (selectItems.length > 0 && answer !== "" && content !== "" && courseId !== 0) {
          return true;
        } else {
          message.info("请填写必填项信息");
          return false;
        }
      } else {
        if (answer !== "" && content !== "" && courseId !== 0) {
          return true;
        } else {
          message.info("请填写必填项信息");
          return false;
        }
      }
    } else {
      message.info("请选择类型");
      return false;
    }
  }

  //选择题正确选项
  renderCheckBox() {
    const checked = this.state.answer.split(',');
    const nums = [];
    checked.forEach((value => {
      nums.push(Number(value))
    }))
    return <Checkbox.Group value={nums} style={{width: '100%'}} onChange={this.onCheckboxChange.bind(this)}>
      <Row>
        {
          this.state.selectItems.map((element, index) => {
            const str = String.fromCharCode(65 + index);
            return <Col key={element.id} span={4}>
              <Checkbox value={index}>{str}</Checkbox>
            </Col>
          })
        }
      </Row>
    </Checkbox.Group>
  }

  /*试题类型变化*/
  onTypeChange = (e) => {
    this.setState({type: e});
    this.clearContent();
  }
  /*添加选择题选项*/
  onCreateSelectItem = () => {
    const value = this.selectOption.Submit();
    const temp = this.state.selectItems;
    let item = {
      id: newGuid(),
      value: value
    }
    temp.push(item);
    this.setState({selectItems: temp, visible: false});
  }
  //删除选项
  onDeleteSelectItem = (value) => {
    const temp = this.state.selectItems;
    temp.forEach((ele, index) => {
      if (ele === value) {
        temp.splice(index, 1);
      }
    })
    this.setState({selectItems: Object.assign([], temp)});
  }
  //取消弹窗
  onCancelModal = () => {
    this.setState({visible: false});
  }
  questionTopic: MdEditor;
  selectOption: MdEditor;

  clearContent() {
    this.questionTopic?.Clear();
    this.setState({
      selectItems: [],
      answer: "",
      analyzing: ""
    });
  }

  renderJudgment() {
    return <div>
      <Select style={{width: 320}} value={this.state.answer} placeholder={"请选择答案"}
              onChange={(e) => {
                this.setState({answer: e});
              }}>
        <Option value={"1"}>正确</Option>
        <Option value={"0"}>错误</Option>
      </Select>
    </div>
  }

  render() {
    const {courseList, type, visible, selectItems} = this.state;
    return (
      <div style={{
        width: "100%",
        height: "auto",
        marginTop: 20
      }}>
        <div style={{width: "100%", display: "flex", justifyContent: "left"}}>
          {/*选择题目类型*/}
          <div id="question-type">
            <h3 className="required">题目类型:</h3>
            <Select style={{width: 320}} value={this.state.type} placeholder={"请选择题目类型"}
                    onChange={this.onTypeChange.bind(this)}>
              <Option value={QuestionType.select}>选择题</Option>
              <Option value={QuestionType.judgment}>判断题</Option>
              <Option value={QuestionType.fill}>填空题</Option>
              <Option value={QuestionType.answer}>简答题</Option>
            </Select>
          </div>
          {/*所属课程*/}
          <div id="question-course" style={{marginLeft: 20}}>
            <h3 className="required">所属课程:</h3>
            <FilterByCourse
              course={courseList}
              style={{margin: 0}}
              courseName={this.state.courseName}
              getValue={(value) => {
                this.setState({courseId: value});
              }}/>
          </div>
        </div>
        {/*题目*/}
        <div id="question-topic" style={{width: "100%", height: "auto", marginTop: 20}}>
          <h3 className="required">试题题目:</h3>
          <MdEditor id={"question-topic-edit"} width={"100%"} height={200} onRef={(ref) => this.questionTopic = ref}/>
        </div>
        {
          type === QuestionType.select ? <div>
            {/*选项*/}
            <div id="question-options" style={{height: "auto", marginTop: 20}}>
              <h3 className="required">选项:</h3>
              <div style={{display: "flex", justifyContent: "flex-end", marginBottom: 10}}>
                <Button type="primary" onClick={() => {
                  this.setState({visible: true});
                }}>
                  添加选项
                </Button>
              </div>
              {
                selectItems?.map((element, index) => {
                  return <div key={index}
                              style={{
                                width: "100%",
                                display: "flex",
                                justifyContent: "space-between",
                                alignItems: "center",
                                marginBottom: 10
                              }}>
                    <span>{String.fromCharCode(65 + index) + '. '}</span> <MdDocShow id={element.id}
                                                                                     style={{width: "90%"}}
                                                                                     value={element.value}/>
                    <Button type="primary" danger={true}
                            onClick={this.onDeleteSelectItem.bind(this, element)}>删除</Button>
                  </div>
                })
              }
            </div>
          </div> : null
        }

        {/*正确答案*/}
        <div id="correct-answer">
          <h3 className="required">正确答案:</h3>
          {
            type === QuestionType.select ?
              <div>
                {
                  this.renderCheckBox()
                }
              </div>
              : type === QuestionType.judgment ?
              <div>
                {this.renderJudgment()}
              </div> :
              <Input.TextArea value={this.state.answer} showCount={true} maxLength={100} onChange={(e) => {
                this.setState({answer: e.target.value});
              }}/>

          }
        </div>
        {/*解析*/}
        <div id="parsing">
          <h3>解析:</h3>
          <Input.TextArea value={this.state.analyzing} showCount={true} maxLength={100} onChange={(e) => {
            this.setState({analyzing: e.target.value});
          }}/>
        </div>
        <div style={{marginTop: 20, display: "flex", justifyContent: "flex-end"}}>
          <Button style={{marginRight: 20}} onClick={() => {
            this.props.history.push({
              pathname: '/teaching/exam/question'
            });
          }}>
            退出
          </Button>
          <Button type="primary" onClick={this.createNewQuestion.bind(this)}>
            提交
          </Button>
        </div>
        <Modal title="添加选项"
               width={800}
               visible={visible}
               destroyOnClose={true}
               onOk={this.onCreateSelectItem}
               onCancel={this.onCancelModal}>
          <MdEditor width={"100%"} height={200} id={"question-select-item"} onRef={(ref) => this.selectOption = ref}/>
        </Modal>
      </div>
    );
  }
}

export default CreateNewQuestion;

enum QuestionType {
  select = 1,
  judgment,
  fill,
  answer
}
